import socket
import threading
import json
import os
import sys

#这是单个客户端连接的服务端代码

FILE = os.path.abspath('./file')
sys.path.append(FILE)
import file as f




#服务器文件缓存
global server_file_buff
server_file_buff={}



def server_send_data(data):
    global new_socket
    new_socket.send(data.encode())




#服务接收数据的处理
def server_receive_data_handle(buf):
    # print(buf)

    data = {}
    #尝试转为json
    try:
        data=json.loads(buf)
    except ValueError:
        print("not json")
        return 
    
    if data['operation'] == "close_server":
        server_send_data('{"operation":"close_server","state":True}')
        exit()

    if data['operation'] == "update_file":
        global server_file_buff
        server_file_buff={}
        server_file_buff['name']=data['name']
        server_file_buff['update']=data['update']
        f.file__openWrite(server_file_buff['name'],server_file_buff['update'])
        server_send_data('{"operation":"update_file","state":True}')
        # print(server_file_buff)

    if data['operation'] == "getdate_file":
        server_file_buff={}
        server_file_buff['name']=data['name']
        server_file_buff['getdate'] = f.file__openRead(server_file_buff['name'])
        server_send_data('{"operation":"update_file","state":True,"getdate":"'+server_file_buff['getdate']+'"}')



#服务端接收处理线程
def server_receive_handle_thread():
    global new_socket,client_ip_port
    global server_socket
    while 1:
        #阻塞等待客户端连接
        new_socket, client_ip_port = server_socket.accept()
        while 1:
            # 5 新的socket收信息
            buf = new_socket.recv(4096)
            if buf:
                server_receive_data_handle(buf.decode())
                # print(buf.decode())
                # 6 新的socket发信息
                # send_data = (f'{client_ip_port}连接成功').encode()
                # new_socket.send(send_data)
            else:
                print(f'客户端{client_ip_port}断开连接')
                break
        new_socket.close()


def server_init():
    global server_socket
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 2 绑定 IP 和端口
    # server_socket.bind(('电脑本机IP',8888))
    server_socket.bind(('',9999)) # 前面空，绑定服务器的任意一个网卡
    # 3 监听，参数是同时连接的客户端数量
    server_socket.listen(128)
    sub_thread = threading.Thread(target=server_receive_handle_thread  )
    sub_thread.start()


